package one.stand.controller;

import com.jmp.base.dto.OrderPayWxAlipayBackDto;
import com.jmp.base.dto.OrderPayWxAppBackDto;
import com.jmp.feign.OrderFeign;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import one.stand.model.ResultModel;
import one.stand.util.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author cjr
 */
@Api(description = "支付回调")
@Controller
@RequestMapping("pay")
@Slf4j
public class PayController {

    @Autowired
    private OrderFeign orderFeign;

    /**
     * 25小时以内完成8次通知（通知的间隔频率一般是：4m,10m,10m,1h,2h,6h,15h）；
     */
    @RequestMapping(value = "/alipay")
    @ResponseBody
    public String alipay(HttpServletRequest request) {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        try {
            ResultModel resultModel = orderFeign.payAlipayBack(OrderPayWxAlipayBackDto.builder().params(params).build());
            AssertUtil.isTrue(resultModel);

            return "success";
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return "error";
    }

    @RequestMapping(value = "/wx/app")
    @ResponseBody
    public String wxApp(HttpServletRequest request) {
        try {
            BufferedReader reader = request.getReader();
            String line = "";
            StringBuffer inputString = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                inputString.append(line);
            }
            request.getReader().close();
            ResultModel resultModel = orderFeign.payWxAppBack(OrderPayWxAppBackDto.builder()
                    .notifyData(inputString.toString())
                    .build());
            AssertUtil.isTrue(resultModel);

            return success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return fail();
    }

    private String success() {
        return "<xml> \n" +
                "  <return_code><![CDATA[success]]></return_code>\n" +
                "  <return_msg><![CDATA]></return_msg>\n" +
                "</xml>";
    }

    private String fail() {
        return "<xml> \n" +
                "  <return_code><![CDATA[fail]]></return_code>\n" +
                "  <return_msg><![CDATA[OK]]></return_msg>\n" +
                "</xml>";
    }
}
